<template>
  <div class="club-list">
    <div class="page-header">
      <div class="header-title">
        <h2>社团列表</h2>
        <span class="subtitle">管理所有已注册社团</span>
      </div>
      <div class="header-actions">
        <!-- <el-button type="primary" icon="el-icon-plus" @click="handleAddClub">添加社团</el-button> -->
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="社团名称">
          <el-input v-model="filterForm.title" placeholder="请输入社团名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="社团类型">
          <el-input v-model="filterForm.tags" placeholder="请输入社团类型" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-select v-model="filterForm.stat" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="已禁用" :value="2"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <!-- <div class="table-operations">
        <el-button-group>
          <el-button size="small" @click="handleBatchExport">导出数据</el-button>
          <el-button size="small" @click="handleRefresh">刷新</el-button>
        </el-button-group>
      </div> -->
      
      <el-table
        :data="clubList"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection"></el-table-column> -->
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="社团名称">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewClubDetail(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="类型">
          <template slot-scope="scope">
            <template v-if="scope.row.tags">
              <el-tag 
                v-for="(tag, index) in scope.row.tags.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="presidentName" label="负责人" width="120"></el-table-column> -->
        <!-- <el-table-column prop="memberCount" label="成员数" width="100"></el-table-column> -->
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="stat" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.stat === 1 ? 'success' : scope.row.stat === 0 ? 'warning' : 'danger'">
              {{ scope.row.stat === 1 ? '正常' : scope.row.stat === 0 ? '待审核' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="viewClubDetail(scope.row)">查看详情</el-button>
            <!-- <el-button type="text" size="small" @click="editClub(scope.row)">编辑</el-button> -->
            <!-- <el-button 
              type="text" 
              size="small" 
              :class="{ 'danger-button': scope.row.stat === 1 }"
              @click="toggleClubStatus(scope.row)">
              {{ scope.row.stat === 1 ? '禁用' : '启用' }}
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 社团详情对话框 -->
    <el-dialog title="社团详情" :visible.sync="clubDetailVisible" width="70%">
      <div v-if="currentClub" class="club-detail">
        <!-- 添加社团头像和公告图片展示区域 -->
        <div class="club-images">
          <div class="club-avatar-container">
            <h4>社团Logo</h4>
            <div class="club-image-wrapper">
              <img 
                :src="currentClub.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" 
                alt="社团Logo" 
                class="club-avatar" />
            </div>
          </div>
          <div class="club-placard-container">
            <h4>社团公告图片</h4>
            <div class="club-image-wrapper">
              <img 
                :src="currentClub.placard || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'" 
                alt="社团公告" 
                class="club-placard" />
            </div>
          </div>
        </div>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="社团名称">{{ currentClub.name }}</el-descriptions-item>
          <el-descriptions-item label="社团类型">
            <template v-if="currentClub.category">
              <el-tag 
                v-for="(tag, index) in currentClub.category.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentClub.president }}</el-descriptions-item>
          <el-descriptions-item label="成员数量">{{ clubMembers.length }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentClub.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentClub.status === '正常' ? 'success' : currentClub.status === '待审核' ? 'warning' : 'danger'">
              {{ currentClub.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="社团简介" :span="2">{{ currentClub.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h3>核心成员</h3>
          <el-table :data="clubMembers" style="width: 100%" v-loading="!clubMembers.length">
            <el-table-column prop="nickname" label="昵称"></el-table-column>
            <el-table-column prop="position" label="职位">
              <template slot-scope="scope">
                <el-tag :type="scope.row.position === '部长' ? 'primary' : 'success'">{{ scope.row.position || '成员' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <!-- <el-table-column prop="" label="专业"></el-table-column> -->
            <!-- <el-table-column prop="grade" label="年级"></el-table-column> -->
          </el-table>
          <div v-if="clubMembers.length === 0" class="empty-data">
            <i class="el-icon-user"></i>
            <p>暂无成员数据</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑社团对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="clubForm" :rules="clubRules" ref="clubForm" label-width="100px">
        <el-form-item label="社团名称" prop="title">
          <el-input v-model="clubForm.title"></el-input>
        </el-form-item>
        <el-form-item label="社团类型" prop="tags">
          <el-input v-model="clubForm.tags" placeholder="请输入社团类型，多个类型用逗号分隔"></el-input>
          <div class="form-tip">多个类型请用逗号分隔，如：学术科技,文化艺术</div>
        </el-form-item>
        <el-form-item label="负责人" prop="presidentName">
          <el-input v-model="clubForm.presidentName"></el-input>
        </el-form-item>
        <el-form-item label="社团简介" prop="description">
          <el-input type="textarea" v-model="clubForm.description" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="stat">
          <el-select v-model="clubForm.stat" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="1"></el-option>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="已禁用" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitClubForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";

export default {
  name: 'ClubList',
  data() {
    return {
      loading: false,
      filterForm: {
        title: '',
        tags: '',
        stat: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      clubList: [],
      selectedRows: [],
      clubDetailVisible: false,
      currentClub: null,
      editDialogVisible: false,
      dialogTitle: '添加社团',
      clubForm: {
        id: '',
        title: '',
        tags: '',
        description: '',
        stat: 1
      },
      clubRules: {
        title: [
          { required: true, message: '请输入社团名称', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择社团类型', trigger: 'change' }
        ]
      },
      clubActivities: [
        { content: '举办迎新晚会', time: '2023-09-15', type: 'success' },
        { content: '参加校园文化节', time: '2023-10-20', type: 'primary' },
        { content: '组织专业技能培训', time: '2023-11-05', type: 'info' }
      ],
      clubMembers: []
    }
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.fetchClubList();
  },
  methods: {
    fetchClubList() {
      this.loading = true;
      
      const params = {
        title: this.filterForm.title || undefined,
        tags: this.filterForm.tags || undefined,
        stat: this.filterForm.stat !== '' ? this.filterForm.stat : undefined
      };
      
      Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);
      
      httpInstance.post('/api/club/search', params)
        .then(res => {
          if (res.code === 200) {
            this.clubList = res.data;
            this.pagination.total = res.data.length;
          } else {
            this.$message.error(res.msg || '获取社团列表失败');
          }
        })
        .catch(err => {
          console.error('获取社团列表失败:', err);
          this.$message.error('获取社团列表失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchClubList();
    },
    
    resetForm() {
      this.filterForm = {
        title: '',
        tags: '',
        stat: ''
      };
      this.fetchClubList();
    },
    
    handleRefresh() {
      this.fetchClubList();
    },
    
    handleBatchExport() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要导出的社团');
        return;
      }
      
      this.$message.success(`已选择${this.selectedRows.length}个社团进行导出`);
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    viewClubDetail(club) {
      this.currentClub = {
        name: club.title,
        category: club.tags,
        createTime: this.formatDate(club.createTime),
        status: club.stat === 1 ? '正常' : club.stat === 0 ? '待审核' : '已禁用',
        description: club.description || '暂无描述',
        avatar: club.avatar,
        placard: club.placard
      };
      
      // 获取社团负责人信息
      httpInstance.get(`/api/club/president/${club.id}`)
        .then(res => {
          console.log("负责人", res);
        
          if (res.code === 200) {
            this.currentClub.president = res.data.nickname || '未指定';
          } else {
            this.currentClub.president = '获取失败';
            this.$message.error(res.msg || '获取负责人信息失败');
          }
        })
        .catch(err => {
          console.error('获取负责人信息失败:', err);
          this.currentClub.president = '获取失败';
        });
      
      // 获取社团成员信息
      httpInstance.get(`/api/club/members/${club.id}`)
        .then(res => {
          console.log("成员", res);
          
          if (res.code === 200) {
            this.clubMembers = res.data || [];
          } else {
            this.clubMembers = [];
            this.$message.error(res.msg || '获取成员列表失败');
          }
        })
        .catch(err => {
          console.error('获取成员列表失败:', err);
          this.clubMembers = [];
        });
      
      this.clubDetailVisible = true;
    },
    
    editClub(club) {
      this.dialogTitle = '编辑社团';
      this.clubForm = {
        id: club.id,
        title: club.title,
        tags: club.tags,
        description: club.description,
        stat: club.stat
      };
      this.editDialogVisible = true;
    },
    
    handleAddClub() {
      this.dialogTitle = '添加社团';
      this.clubForm = {
        id: '',
        title: '',
        tags: '',
        description: '',
        stat: 1
      };
      this.editDialogVisible = true;
    },
    
    submitClubForm() {
      this.$refs.clubForm.validate(async (valid) => {
        if (valid) {
          try {
            const isEdit = !!this.clubForm.id;
            const url = isEdit ? `/api/club/update/${this.clubForm.id}` : '/api/club/create';
            const method = isEdit ? 'put' : 'post';
            
            const response = await httpInstance[method](url, this.clubForm);
            
            if (response && response.code === 200) {
              this.$message.success(isEdit ? '编辑成功' : '添加成功');
              this.editDialogVisible = false;
              this.fetchClubList();
            } else {
              this.$message.error(response?.msg || (isEdit ? '编辑失败' : '添加失败'));
            }
          } catch (error) {
            console.error(this.clubForm.id ? '编辑社团失败:' : '添加社团失败:', error);
            this.$message.error(this.clubForm.id ? '编辑失败，请稍后重试' : '添加失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    
    toggleClubStatus(club) {
      const action = club.stat === 1 ? '禁用' : '启用';
      const newStatus = club.stat === 1 ? 2 : 1;
      
      this.$confirm(`确定要${action}该社团吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: club.stat === 1 ? 'warning' : 'info'
      }).then(async () => {
        try {
          const url = `/api/club/update-status/${club.id}`;
          const response = await httpInstance.post(url, { stat: newStatus });
          
          if (response && response.code === 200) {
            this.$message.success(`${action}成功`);
            this.fetchClubList();
          } else {
            this.$message.error(response?.msg || `${action}失败`);
          }
        } catch (error) {
          console.error(`${action}社团失败:`, error);
          this.$message.error(`${action}失败，请稍后重试`);
        }
      }).catch(() => {
        // 取消操作
      });
    },
    
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchClubList();
    },
    
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchClubList();
    },
    
    getTagType(category) {
      category = category.trim();
      const typeMap = {
        '学术科技': 'primary',
        '文化艺术': 'success',
        '体育运动': 'warning',
        '社会实践': 'danger',
        '志愿公益': 'info'
      };
      
      if (typeMap[category]) {
        return typeMap[category];
      }
      
      if (category.includes('学术') || category.includes('科技')) return 'primary';
      if (category.includes('文化') || category.includes('艺术')) return 'success';
      if (category.includes('体育') || category.includes('运动')) return 'warning';
      if (category.includes('社会') || category.includes('实践')) return 'danger';
      if (category.includes('志愿') || category.includes('公益')) return 'info';
      
      return '';
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.club-list {
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-button {
  color: #F56C6C;
}

.detail-section {
  margin-top: 30px;
}

.detail-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

/* 添加表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  padding-top: 4px;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.empty-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

/* 社团图片展示样式 */
.club-images {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.club-avatar-container, 
.club-placard-container {
  flex: 1;
}

.club-image-wrapper {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.club-avatar {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 50%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.club-placard {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}
</style>
